//
//  HMNetworkTools.swift
//  SwiftAFN独立封装测试
//
//  Created by 艾小新 on 16/8/3.
//  Copyright © 2016年 xiaoxin. All rights reserved.
//

import UIKit
import AFNetworking

enum HMMethod : String {
    case GET = "GET"
    case POST = "POST"

}




class HMNetworkTools: AFHTTPSessionManager {
    
    // 单例
    static var sharedTools: HMNetworkTools = {
       
        let tools = HMNetworkTools()
        tools.responseSerializer.acceptableContentTypes?.insert("text/html")
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools   
    }()
    
    typealias HMCallback = ((returnData: AnyObject?, errors:NSError?)->())
    
    
    
    
    func requestData(method:HMMethod, urlString:String, parameter:AnyObject?, callBack:HMCallback) {
        
        let med = method == HMMethod.GET ? "GET": "POST"
        
        // 可以把闭包提取出来
        let success = { (dataTask:NSURLSessionDataTask, returnData:AnyObject?)  in
            
            
            callBack(returnData:returnData,errors:nil)

        }
        
        
        // 可以把闭包提取出来
        let failed = { (dataTask:NSURLSessionDataTask?, error:NSError)  in
            callBack(returnData:nil,errors:error)
            
        }
        if med == "GET" {
            GET(urlString, parameters: parameter, progress: nil, success: success, failure: failed)
 
        } else {
            POST(urlString, parameters: parameter, progress: nil, success: success, failure: failed)
  
            
        }
        
        
        
        
    }
    
    
    

}

// MARK: - 发送微博相关请求的方法
extension HMNetworkTools {
    
    /// 发表图片微博
    ///
    /// - parameter status: <#status description#>
    func upload(status: String, image: UIImage, callback: HMCallback){
        
        guard let accessToken = HMUserLoginViewModel.sharedUserLoginViewModel.accessToken else {
            callback(returnData: nil, errors: nil)
            return
        }
        
        // 请求地址
        let urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
        // 请求方式
        let parameters = [
            "access_token" :accessToken,
            "status": status
        ]
        
        self.POST(urlString, parameters: parameters, constructingBodyWithBlock: { (formdata) -> Void in
            let data = UIImagePNGRepresentation(image)!
            // 拼接图片数据需要的闭包
            /**
             - 参数1:name -> 接口里面对应该文件的字段
             - 参数2:fileName ->
             - 参数3:mimeType --> 告诉后台我要传给你的文件是什么类型的
             - 大类型/小类型
             - image/png text/html text/json
             - 如果不知道是什么类型的话: application/octet-stream
             */
            formdata.appendPartWithFileData(data, name: "pic", fileName: "aabb", mimeType: "application/octet-stream")
            }, progress: nil, success: { (_, responseObject) -> Void in
                
                guard let dict = responseObject as? [String: AnyObject] else{
                    // 如果发现不是字典
                    callback(returnData: nil, errors: NSError(domain: "com.itheima.hahaha", code: 10001, userInfo: ["message": "返回数据不是字典"]))
                    return
                }
                
                // 请求成功回调的闭包
                callback(returnData: dict, errors: nil)
        }) { (_, error) -> Void in
            // 请求失败回调的闭包
            callback(returnData: nil, errors: error)
        }
        
    }
    
    
    /// 发送文字微博的
    ///
    /// - parameter status:   微博内容
    /// - parameter callback: 发送完毕的回调
    func update(status: String, callback: HMCallback){
        
        guard let accessToken = HMUserLoginViewModel.sharedUserLoginViewModel.accessToken else {
            callback(returnData: nil, errors: nil)
            return
        }
        
        // 1. 定义url
        let urlString = "https://api.weibo.com/2/statuses/update.json"
        // 2. 定义参数
        let parameters = [
            "access_token": accessToken,
            "status": status
        ]
        requestData(.POST, urlString: urlString, parameter: parameters, callBack: callback)
    }
    
}

